import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../model/OrderModel.dart';
import '../../config/Config.dart';
import '../../services/ScreenAdapter.dart';
import '../../services/SignServices.dart';
import '../../services/UserServices.dart';
import '../CustomsDeclaration.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> {
  List<OrderModel> _orderList = [];

  @override
  void initState() {
    super.initState();
    _orderList = [
      OrderModel(
        success: true,
        message: "Order fetched successfully",
        result: [
          Result(
            id: "order1",
            uid: "user1",
            name: "张三",
            phone: "+86 13800138000",
            address: "北京市朝阳区某某街道123号",
            allPrice: "697",
            payStatus: 1,
            orderStatus: 2,
            orderItem: [
              OrderItem(
                id: "item1",
                orderId: "order1",
                productTitle: "无线蓝牙耳机",
                productId: "prod1",
                productPrice: 199,
                productImg:
                    "https://t11.baidu.com/it/u=3678476250,168253849&fm=30&app=106&f=JPEG?w=640&h=527&s=E9A31F7045124E650A4C65C80300E0B3",
                productCount: 2,
                selectedAttr: "颜色: 黑色",
                addTime: 1680000000,
              ),
              OrderItem(
                id: "item2",
                orderId: "order1",
                productTitle: "智能手表带GPS",
                productId: "prod2",
                productPrice: 299,
                productImg:
                    "https://qna.smzdm.com/202207/18/62d52bfabe5087765.png_e1080.jpg",
                productCount: 1,
                selectedAttr: "尺寸: M",
                addTime: 1680000001,
              ),
            ],
          ),
        ],
      ),
      OrderModel(
        success: true,
        message: "Order fetched successfully",
        result: [
          Result(
            id: "order1",
            uid: "user1",
            name: "张三",
            phone: "+86 13800138000",
            address: "北京市朝阳区某某街道123号",
            allPrice: "697",
            payStatus: 1,
            orderStatus: 2,
            orderItem: [
              OrderItem(
                id: "item1",
                orderId: "order1",
                productTitle: "无线蓝牙耳机",
                productId: "prod1",
                productPrice: 199,
                productImg:
                    "https://t11.baidu.com/it/u=3678476250,168253849&fm=30&app=106&f=JPEG?w=640&h=527&s=E9A31F7045124E650A4C65C80300E0B3",
                productCount: 2,
                selectedAttr: "颜色: 黑色",
                addTime: 1680000000,
              ),
              OrderItem(
                id: "item2",
                orderId: "order1",
                productTitle: "智能手表带GPS",
                productId: "prod2",
                productPrice: 299,
                productImg:
                    "https://qna.smzdm.com/202207/18/62d52bfabe5087765.png_e1080.jpg",
                productCount: 1,
                selectedAttr: "尺寸: M",
                addTime: 1680000001,
              ),
            ],
          ),
        ],
      ),
    ];
  }

  // 获取订单列表数据
  /*
  void _getListData() async {
    List userinfo = await UserServices.getUserInfo();
    var tempJson = {"uid": userinfo[0]['_id'], "salt": userinfo[0]["salt"]};
    var sign = SignServices.getSign(tempJson);
    var api =
        '${Config.domain}api/orderList?uid=${userinfo[0]['_id']}&sign=$sign';
    var response = await Dio().get(api);
    setState(() {
      var orderMode = OrderModel.fromJson(response.data);
      _orderList = orderMode.result;
    });
  }
  */

// 构建订单项组件
  List<Widget> _orderItemWidget(List<OrderItem> orderItems) {
    List<Widget> tempList = [];
    for (var item in orderItems) {
      String pic = item.productImg;
      // 假设你的图片URL不需要修改
      tempList.add(
        Column(
          children: [
            const SizedBox(height: 10),
            ListTile(
              leading: SizedBox(
                width: ScreenAdapter.width(120),
                height: ScreenAdapter.height(120),
                child: Image.network(
                  pic,
                  fit: BoxFit.cover,
                ),
              ),
              title: Text(item.productTitle),
              trailing: Text('x${item.productCount}'),
            ),
            const SizedBox(height: 10)
          ],
        ),
      );
    }
    return tempList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("我的订单")),
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.fromLTRB(0, ScreenAdapter.height(80), 0, 0),
            padding: EdgeInsets.all(ScreenAdapter.width(16)),
            child: ListView(
              children: _orderList.expand((orderModel) {
                return orderModel.result.map((value) {
                  return InkWell(
                    onTap: () {
                      Get.toNamed("/orderinfo");
                    },
                    child: Card(
                      child: Column(
                        children: [
                          ListTile(
                            title: Text("订单编号：${value.id}",
                                style: const TextStyle(color: Colors.black54)),
                          ),
                          const Divider(),
                          Column(
                            children: _orderItemWidget(value.orderItem),
                          ),
                          const SizedBox(height: 10),
                          ListTile(
                            leading: Text(
                              "合计：￥${value.allPrice}",
                              style: const TextStyle(fontSize: 16),
                            ),
                            trailing: ElevatedButton(
                              onPressed: () {},
                              style: ButtonStyle(
                                  backgroundColor:
                                      MaterialStateProperty.all(Colors.blue)),
                              child: const Text("申请售后"),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }).toList();
              }).toList(),
            ),
          ),
          Positioned(
            top: 0,
            width: ScreenAdapter.width(750),
            height: ScreenAdapter.height(76),
            child: Container(
              width: ScreenAdapter.width(750),
              height: ScreenAdapter.height(76),
              color: Colors.white,
              child: const Row(
                children: [
                  Expanded(
                    child: Text("全部", textAlign: TextAlign.center),
                  ),
                  Expanded(
                    child: Text("待付款", textAlign: TextAlign.center),
                  ),
                  Expanded(
                    child: Text("待收货", textAlign: TextAlign.center),
                  ),
                  Expanded(
                    child: Text("已完成", textAlign: TextAlign.center),
                  ),
                  Expanded(
                    child: Text("已取消", textAlign: TextAlign.center),
                  )
                ],
              ),
            ),
          ),
          Positioned(
            width: ScreenAdapter.width(750),
            height: ScreenAdapter.height(100),
            bottom: 0,
            child: Container(
              decoration: const BoxDecoration(
                border:
                    Border(top: BorderSide(width: 1, color: Colors.black12)),
                color: Colors.white,
              ),
              width: ScreenAdapter.width(750),
              height: ScreenAdapter.height(100),
              padding: const EdgeInsets.all(5),
              child: Stack(
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        SizedBox(
                          width: ScreenAdapter.width(60),
                          child: Checkbox(
                            value: true,
                            activeColor: Colors.pink,
                            onChanged: (bool? value) {},
                          ),
                        ),
                        const Text(
                          "全选",
                        ),
                      ],
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        fixedSize: const Size(100, 40),
                      ),
                      child: const Text(
                        "申报",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      onPressed: () {
                        Get.to(const CustomsDeclarationPage());
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
